package experiments;


import gui.KeyUserFetchWindow;
import gui.ResultsWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DateFormat;
import java.util.Collection;

import de.umass.lastfm.Artist;
import de.umass.lastfm.Caller;
import de.umass.lastfm.Chart;
import de.umass.lastfm.User;
import de.umass.lastfm.cache.FileSystemCache;

public class WeeklyChartsActionListener implements ActionListener{

	private KeyUserFetchWindow kufw;
	private ResultsWindow rw;
	private String key;
	
	public WeeklyChartsActionListener(String key) {
		this.key = key;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(kufw.getUser().isEmpty()) return;
		kufw.dispose();
		
		//Setup the cache directory.
	    File dataFolder = new File("./cache");
	    if (!dataFolder.isDirectory()) {
	        dataFolder.mkdir();
	    }
	    Caller.getInstance().setCache(new FileSystemCache(dataFolder));
	    
	    //Fetches the user name.
	    String user = kufw.getUser();
		
		//Calls last.fm.
	    Chart<Artist> chart = User.getWeeklyArtistChart(user, 25, key);
	    DateFormat format = DateFormat.getDateInstance();
	    String from = format.format(chart.getFrom());
	    String to = format.format(chart.getTo());
	    rw = new ResultsWindow("Weekly charts for " + user);
	    rw.println(String.format("Charts for %s for the week from %s to %s:%n", user, from, to));
	    Collection<Artist> artists = chart.getEntries();
	    for (Artist artist : artists) {
	        rw.println(artist.getName());
	    }
	    rw.adjustSize();
	}

	public void registerWindow(KeyUserFetchWindow kufw) {
		this.kufw = kufw;
	}

	
}
